package com.example.handler.impl;

import java.util.List;
import java.util.Optional;

import com.baomidou.plugin.idea.mybatisx.dom.model.Mapper;
import com.baomidou.plugin.idea.mybatisx.util.MapperUtils;
import com.example.util.SqlIdFinder;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.xml.XmlTag;

/**
 * @author Aaron
 * @since 2020/11/8 16:21
 * <p>描述：</p>
 */
public class MapperGoToImplHandler extends BaseGoToImplHandler {

    private final AnActionEvent anActionEvent;
    private final PsiClass currentPsiClass;
    private final PsiMethod currentPsiMethod;

    public MapperGoToImplHandler(AnActionEvent anActionEvent, PsiClass currentPsiClass, PsiMethod currentPsiMethod) {
        this.anActionEvent = anActionEvent;
        this.currentPsiClass = currentPsiClass;
        this.currentPsiMethod = currentPsiMethod;
    }

    @Override
    public void doHandle() {
        super.doHandle();

        // 获取当前 Project
        Project project = anActionEvent.getProject();
        if (project == null) {
            System.out.println("Can't get the project by the action event.");
            return;
        }
        if (currentPsiClass == null) {
            return;
        }
        PsiClass psiClass = currentPsiClass;
        if (!psiClass.isInterface()) {
            final PsiClass[] interfaces = psiClass.getInterfaces();
            if (interfaces.length != 0) {
                psiClass = interfaces[0];
            }
        }
        if (psiClass == null) {
            return;
        }
        final Optional<Mapper> mapper = MapperUtils.findFirstMapper(project, psiClass);
        if (mapper.isPresent()) {
            XmlTag tagByMapper = MapperUtils.findTagByMapper(mapper.get(), currentPsiMethod.getName());
            if (tagByMapper == null) {
                final List<String> sqlIdsInComplexCases = SqlIdFinder.findStringsInConcreteImplementation(
                    currentPsiMethod);
                for (String id : sqlIdsInComplexCases) {
                    if (id.contains(".")) {
                        id = id.substring(id.lastIndexOf(".") + 1);
                    }
                    tagByMapper = MapperUtils.findTagByMapper(mapper.get(), id);
                    if (tagByMapper != null) {
                        break;
                    }
                }
            }
            if (tagByMapper != null) {
                NavigationUtil.activateFileWithPsiElement(tagByMapper, true);
            }
        }
    }

}
